<template>
  <el-upload
    style="display:inline-block"
    :class="className"
    :action="action"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :on-success="handleSuccess"
    :on-error="handleError"
    :before-upload="beforeUpload"
    :before-remove="beforeRemove"
    :limit="1"
    :show-file-list="showFileList"
    :on-exceed="handleExceed"
    :file-list="fileList"
    :type-list="typeList"
    :multiple="multiple">
      <el-button :loading="uploading" size="small" :type="buttonType">{{buttonText}}</el-button>
      <div v-if="showHint" slot="tip" class="el-upload__tip">
        只能上传{{typeList}}文件
      </div>
  </el-upload>
</template>
<script>
export default {
  name: 'AnnexUploadButton',
  props: {
    className: {
      type: String,
      default: 'upload-btn'
    },
    buttonText: {
      type: String,
      default: '上传附件'
    },
    buttonType: {
      type: String,
      default: 'primary'
    },
    action: {
      type: String,
      default: '/srm-admin/annex/upload'
    },
    showHint: {
      type: Boolean,
      default: false
    },
    showFileList: {
      type: Boolean,
      default: false
    },
    typeList: {
      type: String,
      default: 'jpg/jpge/png/pdf'
    },
    multiple: {
      type: Boolean,
      default: false
    },
    sizeLimit: {
      type: Number,
      default: 3
    }
  },
  data () {
    return {
      uploading: false,
      fileList: []
    }
  },
  methods: {
    handlePreview (x) {
      // console.log('handlePreview :>> ', x);
    },
    beforeRemove (x) {
      // console.log('beforeRemove :>> ', x);
    },
    beforeUpload (file) {
      const isLt3M = file.size / 1024 / 1024 < this.sizeLimit;
      const type = file.name.split('.').slice(-1)[0]
      // console.log('type :>> ', type);
      if (!this.typeList.split('/').includes(type)) {
        this.$message.error(`只能上传${this.typeList}文件！`)
        return false
      }
      if (!isLt3M) {
        this.$message.error(`上传文件大小不能超过 ${this.sizeLimit}MB！`);
        return false
      }
      this.uploading = true
    },
    handleRemove (x) {
      // console.log('handleRemove :>> ', x);
    },
    handleExceed (x) {
      // console.log('handleExceed :>> ', x);
    },
    handleSuccess (response, file, fileList) {
      this.uploading = false
      this.$emit('onUploaded', { response, file })

      // 值回显父组件
      this.$emit('input', response.result);
      // change事件
      this.$emit('change', response.result)
      this.fileList = []
    },
    handleError () {
      this.$message.error(`文件上传出错！`)
      this.uploading = false
    }
  },
}
</script>
